<template>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="收货人" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="手机号" prop="tell">
      <el-input v-model="ruleForm.tell"></el-input>
    </el-form-item>
    <el-form-item label="所在地" prop="city">
      <el-input v-model="ruleForm.city"></el-input>
    </el-form-item>
    <el-form-item label="详细地址" prop="address">
      <el-input v-model="ruleForm.address"></el-input>
    </el-form-item>
    <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
    </el-form-item>
  </el-form>
</template>
  <script>
    export default {
      data() {
        return {
            index: -1,
            ruleForm: {
            name: '',
            tell: '',
            city: '',
            address: ''
          },
          rules: {
            name: [
              { required: true, message: '请输入姓名', trigger: 'blur' },
            ],
            tell: [
              { required: true, message: '请输入手机号', trigger: 'blur' },
            ],
            city: [
              { required: true, message: '请输入地址', trigger: 'blur' },
            ],
            address: [
              { required: true, message: '请输入详细地址', trigger: 'blur' },
            ],
          },
        };
      },
      methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.index === -1){
            this.$store.commit("add",{ ...this.ruleForm });
            this.$message({
            message: '添加成功',
            type: 'success',
          });
        } else {
            this.$store.commit("edit", {
                index: this.index,
                item: { ...this.ruleForm }
              });
           this.$message({
                message: '修改成功',
                type: 'success'
            });
        }
          this.$router.push('/views/list')
         } else {
            console.log('添加失败');
            return false;
          }
        });
      },
    },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      mounted() {
        if(this.$route.query.item) {
          this.index = this.$route.query.index;
          this.ruleForm = JSON.parse(this.$route.query.item || '{}');
        }
      },  
};
</script>

<style lang="scss" scoped>

</style>

  